package by.amakarevich.dataaccess.Impl;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.amakarevich.dataaccess.ShoppingCartDao;
import by.amakarevich.datamodel.ShoppingCart;
import by.amakarevich.datamodel.ShoppingCart_;
import by.amakarevich.datamodel.UserAccount;

@Repository
public class ShoppingCartDaoImpl extends AbstractDaoImpl<Long, ShoppingCart> implements ShoppingCartDao {
	protected ShoppingCartDaoImpl(){
		super(ShoppingCart.class);
	}
	
	@Override
	public ShoppingCart getByUser(UserAccount user){
		CriteriaBuilder cBuilder= getEm().getCriteriaBuilder();
		  CriteriaQuery<ShoppingCart> criteria=cBuilder.createQuery(ShoppingCart.class);
		  Root<ShoppingCart> root=criteria.from(ShoppingCart.class);
		  
		  criteria.select(root);
	      root.fetch(ShoppingCart_.userAccount);
	      criteria.distinct(true);
		  criteria.where(cBuilder.equal(root.get(ShoppingCart_.userAccount),user.getId()));

		  TypedQuery<ShoppingCart> query = getEm().createQuery(criteria);
		  ShoppingCart results = (ShoppingCart)query.getSingleResult();
	      return results;
		
	}
}
